﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;

public partial class ValidateCode : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //字体大小
        int font_size = 14;
        int width = 0;

        //使用纯数字做验证码
        //string validate_str = Random_Number(4);
        //使用数字加字母
        string validate_str = Random_String(4);
        width = validate_str.Length * (font_size + 2);//计算宽度              

        //使用中文
        //string validate_str = Random_Chinese(4);
        //使用中文加数字加字母
        //string validate_str = Random_Chinese_Char(4);
        //width = validate_str.Length * (font_size)*2 ;

        //创建图像
        Create_Validate_Image(validate_str, width, 32, font_size);

        //写入Cookie
        //Response.Cookies.Add(new HttpCookie("ValidateCode",validate_str)); 
        //写入Session
        Session["validateKey"] = validate_str;
    }

    /// <summary>
    /// 生成随机数字
    /// </summary>
    /// <param name="size">需要的数字个数</param>
    /// <returns>生成的字符串</returns>
    private string Random_Number(int size)
    {
        int number;
        char code;
        string validate_str = string.Empty;
        System.Random random = new Random();
        for (int i = 0; i < size; i++)
        {
            //返回一个指定范围内的随机数
            number = random.Next(48, 57); //48,57为ASCII码:0-9
            code = (char)(number);
            validate_str += code;
        }
        return validate_str;
    }

    /// <summary>
    ///生成随机数字加字母
    /// </summary>
    /// <param name="validate_string_size">字符串长度</param>
    /// <returns>字符串</returns>
    private string Random_String(int validate_string_size)
    {
        string vchar = "23456789ABCDEGHKMNPQRSUVWXYZ";
        string vnum = "";
        System.Random rand = new Random();
        for (int i = 0; i < validate_string_size; i++)
        {
            int t = rand.Next(vchar.Length);
            vnum += vchar[t];
        }
        return vnum;
    }

    /// <summary>
    /// 生成中文验证码字符串
    /// </summary>
    /// <param name="validate_string_size">字符个数</param>
    /// <returns>验证码字符串</returns>
    private string Random_Chinese(int validate_string_size)
    {
        //string vchar = "2,3,4,5,6,7,8,9,a,b,c,d,e,g,h,k,m,n,p,q,r,s,u,v,w,x,y,z";
        //这个字符源比较少,字也常用,适合五笔用户输入
        string cchar = "我人有的和主产不为这工要在地一上是中国同经以发了民搜索就计算机业学习科技美女东西南北";
        //这个字符源比较多,字的笔划少,(输入法还没考虑),
        //string cchar = "乙十丁厂七卜人九几儿了力乃刀又三于干亏士工土才寸下大丈与万上小口巾山千乞川亿个勺久凡及夕丸么广亡门义之尸弓己已子卫也女飞刃习叉马乡丰王井开夫天无元专云扎艺木五支厅不太犬区历尤友匹车巨牙屯比互切瓦止少日中冈贝内水见午牛手毛气升长仁什片仆化仇币仍仅斤爪反介父从今凶分乏公仓月氏勿欠风丹匀乌凤勾文六方火为斗忆订计户认心尺引丑巴孔队办以允予劝双书幻玉刊示末未击打巧正扑扒功扔去甘世古节本术可丙左厉右石布龙平灭轧东卡北占业旧帅归且旦目叶甲申叮电号田由史只央兄叼叫另叨叹四生失禾丘付仗代仙们仪白仔他斥瓜乎丛令用甩印乐句匆册犯外处冬鸟务包饥主市立闪兰半汁汇头汉宁穴它讨写让礼训必议讯记永司尼民出辽奶奴加召皮边发孕圣";
        string vnum = "";
        System.Random rand = new Random();
        for (int i = 0; i < validate_string_size; i++)
        {
            int t = rand.Next(cchar.Length);
            vnum += cchar[t];
        }
        return vnum;
    }

    /// <summary>
    /// 生成中英文数字验证码字符串
    /// </summary>
    /// <param name="validate_string_size">字符个数</param>
    /// <returns>验证码字符串</returns>
    private string Random_Chinese_Char(int validate_string_size)
    {
        string vchar = "23456789ABCDEGHKMNPQRSUVWXYZ我人有的和九主产不七为这工要十在地一上八是中国同经以四发了五民搜索就计六算机合肥业学习科技安徽美女东西南北二三";
        string vnum = "";
        System.Random rand = new Random();
        for (int i = 0; i < validate_string_size; i++)
        {
            int t = rand.Next(vchar.Length);
            vnum += vchar[t];
        }
        return vnum;
    }

    /// <summary>
    /// 生成图像
    /// </summary>
    /// <param name="validate_str">随机字符串</param>
    /// <param name="width">图片宽度</param>
    /// <param name="height">图片高度</param>
    /// <param name="font_size">字体大小</param>
    private void Create_Validate_Image(string validate_str, int width, int height, int font_size)
    {
        if (validate_str == null || validate_str.Trim() == String.Empty)
            return;

        System.Drawing.Bitmap validate_image = new System.Drawing.Bitmap(width, height);
        Graphics g = Graphics.FromImage(validate_image);
        try
        {
            //生成随机生成器
            Random random = new Random();

            //清空图片背景色
            g.Clear(Color.White);

            //画图片的背景噪音线,15为噪音线条数
            for (int i = 0; i < 15; i++)
            {
                int x1 = random.Next(validate_image.Width);
                int x2 = random.Next(validate_image.Width);
                int y1 = random.Next(validate_image.Height);
                int y2 = random.Next(validate_image.Height);
                g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
            }
            //画字符串
            //文字字体
            Font font = new System.Drawing.Font("Arial", font_size, (System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic));
            //文字颜色
            //带渐变得效果
            //System.Drawing.Drawing2D.LinearGradientBrush brush = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, validate_image.Width, validate_image.Height), Color.Blue, Color.Black, 1.2f, true);
            //普通单色 
            System.Drawing.SolidBrush brush = new System.Drawing.SolidBrush(Color.Green);
            g.DrawString(validate_str, font, brush, 0, (height / 2 - 3 * font_size / 4));
            //画图片的前景噪音点,50为噪音点数
            for (int i = 0; i < 50; i++)
            {
                int x = random.Next(validate_image.Width);
                int y = random.Next(validate_image.Height);
                validate_image.SetPixel(x, y, Color.FromArgb(random.Next()));
            }
            //画图片的边框线 
            g.DrawRectangle(new Pen(Color.Silver), 0, 0, validate_image.Width - 1, validate_image.Height - 1);
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            validate_image.Save(ms, ImageFormat.Gif);
            Response.ClearContent();
            Response.ContentType = "image/GIF";
            Response.BinaryWrite(ms.ToArray());
        }
        finally
        {
            g.Dispose();
            validate_image.Dispose();
        }
    }
}